package com.codingchili.logging.model;

import io.vertx.core.shareddata.Shareable;

import java.util.HashMap;
import java.util.Map;

import com.codingchili.core.protocol.Serializer;
import com.codingchili.core.storage.JsonStorable;
import com.codingchili.core.storage.Storable;

/**
 * @author Robin Duda
 * <p>
 * Contains the entire statistics model, lazy persist - memory read.
 */
public class StatisticModel implements Storable {
    private PlayerLeaderboard leaderboard = new PlayerLeaderboard();
    private Map<String, Counters> counters = new HashMap<>();
    private int accounts = 0;
    private int characters = 0;

    @Override
    public Shareable copy() {
        var model = new StatisticModel();
        model.setAccounts(accounts);
        model.setCharacters(characters);
        model.setLeaderboard(leaderboard.copy());
        counters.forEach((key, value) -> model.getCounters().put(key, value.copy()));
        return model;
    }

    public void registerAccount() {
        accounts++;
    }

    public void createCharacter() {
        characters++;
    }

    /**
     * @param realm the realm specific counter set to access.
     * @return a counters object for the given realm.
     */
    public Counters realm(String realm) {
        counters.putIfAbsent(realm, new Counters());
        return counters.get(realm);
    }

    public int getCharacters() {
        return characters;
    }

    public void setCharacters(int characters) {
        this.characters = characters;
    }

    public int getAccounts() {
        return accounts;
    }

    public void setAccounts(int accounts) {
        this.accounts = accounts;
    }

    public Map<String, Counters> getCounters() {
        return counters;
    }

    public void setCounters(Map<String, Counters> counters) {
        this.counters = counters;
    }

    public PlayerLeaderboard getLeaderboard() {
        return leaderboard;
    }

    public void setLeaderboard(PlayerLeaderboard leaderboard) {
        this.leaderboard = leaderboard;
    }

    public static String id() {
        return "statistics.object.v1";
    }

    @Override
    public String getId() {
        return StatisticModel.id();
    }

    public JsonStorable toStorable() {
        var storable = new JsonStorable(getId());
        storable.mergeIn(Serializer.json(this));
        return storable;
    }
}
